﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogicLayer;
using CommonUtils;
using Resources;
using EntityDataModel;

namespace LiveCPEProject.wall
{
	public partial class Wall : System.Web.UI.Page
	{
        public String receiverName
        {
            get
            {
                return _receiver;
            }
            set
            {
                _receiver = value;
            }
        }
        private String _receiver;

		protected void Page_Load(object sender, EventArgs e)
		{
            try
            {
                // If the user is NOT logged
                if (!Context.User.Identity.IsAuthenticated)
                {
                    Response.Redirect("~/login/Login.aspx");
                }

                if (!IsPostBack)
                {
                    LoadData();
                }
                else
                {
                    if (Request.Params["userName"] != null) 
                    {
                        receiverName = (String)Request.Params["userName"];
                    }
                    else 
                    {
                        receiverName = Context.User.Identity.Name;
                    }
                }

            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
		}

        protected void LoadData()
        {
            try
            {
                DataList1.ItemDataBound += new DataListItemEventHandler(DataList1_ItemDataBound);

                // If we try to see someone's else wall
                if (Request.Params["userName"] != null)
                {
                    User friend = UserBLL.GetUserByUserName((String)Request.Params["userName"]);
                    // If the user's wall we are trying to reach exist
                    if (friend != null)
                    {
                        receiverName = friend.UserName;
                        FriendUserNameLabel.Text = (String)GetGlobalResourceObject("LocalizedText", "Wall_VisitingBefore") + " " + receiverName + (String)GetGlobalResourceObject("LocalizedText", "Wall_VisitingAfter");
                        WelcomingMessage.Text = (String)GetGlobalResourceObject("LocalizedText", "Wall_LeaveHimAMessage");
                        PanelFriend.Visible = true;

                        // If one's wall we try to look at is a friend
                        if (FriendshipBLL.AreTheyFriends(Context.User.Identity.Name, friend.UserName))
                        {
                            DataList1.DataSource = GetAllMessages(friend.UserName);
                            DataList1.DataBind();
                            DataList1.Visible = true;
                            PanelPostComment.Visible = true;
                            BecomeFriends.Visible = false;
                        }
                        // If one's wall we try to look at is NOT a friend
                        else
                        {
                            BecomeFriends.Visible = true;
                            PanelPostComment.Visible = false;
                            DataList1.Visible = false;
                        }
                    }
                    // If the user's wall we are trying to reach DOES NOT exist
                    else
                    {
                        BecomeFriends.Visible = false;
                        PanelPostComment.Visible = false;
                        DataList1.Visible = false;
                        FriendUserNameLabel.Text = (String)GetGlobalResourceObject("LocalizedText", "Wall_UnknowUser");
                    }
                }
                else
                {
                    receiverName = Context.User.Identity.Name;
                    PanelFriend.Visible = false;
                    DataList1.Visible = true;
                    DataList1.DataSource = GetAllMessages(Context.User.Identity.Name);
                    DataList1.DataBind();
                }
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }

        protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            try
            {
                Label lblMessageContent = ControlFinder.FindControl<Label>(e.Item, "MessageContentLabel");
                LinkButton lkbAcceptRequest = ControlFinder.FindControl<LinkButton>(e.Item, "AcceptRequestButton");
                LinkButton lkbRejectRequest = ControlFinder.FindControl<LinkButton>(e.Item, "RejectRequestButton");
                if (lblMessageContent.Text.Contains((String)GetGlobalResourceObject("LocalizedText", "Wall_WouldYouBeMyFriend")))
                {
                    lblMessageContent.CssClass = "friendRequest";
                    lkbAcceptRequest.Visible = true;
                    lkbRejectRequest.Visible = true;

                }
                DataList dl = ControlFinder.FindControl<DataList>(e.Item, "DataList2");
                Label lblMessageId = ControlFinder.FindControl<Label>(e.Item,"MessageID");
                LinkButton lkb = ControlFinder.FindControl<LinkButton>(e.Item,"LikeLink");
                LinkButton lkc = ControlFinder.FindControl<LinkButton>(e.Item, "LinkComment");
                if (dl != null)
                {
                    List<Comment> comments = GetAllCommentsForMessage(lblMessageId.Text);
                    if (MessageBLL.IsUserAlreadyLikingMessage(Context.User.Identity.Name, lblMessageId.Text))
                    {
                        lkb.Visible = false;
                    }
                    if (comments.Count > 0)
                    {
                        dl.DataSource = comments;
                        dl.DataBind();
                        dl.Visible = true;
                        lkc.Visible = true;
                    }
                }
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }

        protected void Redirect_Click(object sender, EventArgs e)
        {
            try
            {
                Response.Redirect("~/wall/Wall.aspx?userName=" + ((LinkButton)sender).CommandArgument);
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }

        protected void ButtonTwitter_Click(object sender, EventArgs e)
        {
            try
            {
                if (TextBoxStatus.Text.Length > 0)
                {
                    String url = "http://twitter.com/share?via=er3van&url=http://livecpe.codeplex.com/&text=";
                    Response.Write(@"<script language='javascript'>window.open('" + url + TextBoxStatus.Text + "','Twitter','toolbar=yes, location=no, directories=no, status=no, scrollbars=no, resizable=no, copyhistory=no');</script>");
                    if (TextBoxStatus.Text.Length > 150)
                    {
                        TextBoxStatus.Text = TextBoxStatus.Text.Substring(0, 150);
                    }
                    MessageBLL.SendPublicMessage(Context.User.Identity.Name, receiverName, TextBoxStatus.Text);
                    TextBoxStatus.Text = "";
                    LoadData();
                }
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }

        protected void ButtonStatus_Click(object sender, EventArgs e)
        {
            try
            {
                if (TextBoxStatus.Text.Length > 0)
                {
                    if (TextBoxStatus.Text.Length > 150)
                    {
                        TextBoxStatus.Text = TextBoxStatus.Text.Substring(0, 150);
                    }
                    MessageBLL.SendPublicMessage(Context.User.Identity.Name, receiverName, TextBoxStatus.Text);
                    TextBoxStatus.Text = "";
                }
                LoadData();
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }

        protected void UpdateCommentLike_Click(object sender, EventArgs e)
        {
            try
            {
                MessageBLL.LikeComment(Context.User.Identity.Name, ((LinkButton)sender).CommandArgument);
                LoadData();
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }

        protected void UpdateLike_Click(object sender, EventArgs e)
        {
            try
            {
                MessageBLL.LikeMessage(Context.User.Identity.Name, ((LinkButton)sender).CommandArgument);
                LoadData();
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }

        protected void SendComment_Click(object sender, EventArgs e)
        {
            try
            {
                LinkButton lkb = (LinkButton)sender;
                TextBox tb = ControlFinder.FindControl<TextBox>(lkb, "CommentContentTextBox");
                if (tb.Text.Length > 0)
                {
                    if (tb.Text.Length > 150)
                    {
                        tb.Text = tb.Text.Substring(0, 150);
                    }
                    String messageContent = tb.Text;
                    String messageId = lkb.CommandArgument;
                    MessageBLL.AddComment(Context.User.Identity.Name, messageId, messageContent);
                    LoadData();
                }
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }

        protected void TextBoxStatus_Changed(object sender, EventArgs e)
        {
            try
            {
                TextBox tb = (sender as TextBox);
                Button bt = ControlFinder.FindControl<Button>(this, "ButtonStatus");
                if (bt != null)
                {
                    bt.CommandArgument = tb.Text;
                }
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }

        protected void AcceptButton_Click(object sender, EventArgs e)
        {
            try
            {
                FriendshipBLL.AcceptFriendship(((LinkButton)sender).CommandArgument);
                LoadData();
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }

        protected void RejectButton_Click(object sender, EventArgs e)
        {
            try
            {
                FriendshipBLL.RejectFriendship(((LinkButton)sender).CommandArgument);
                LoadData();
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }
        
        protected void BecomeFriends_Click(object sender, EventArgs e)
        {
            try
            {
                FriendshipBLL.CreateFriendship(Context.User.Identity.Name, receiverName);
                BecomeFriends.Text = (String)GetGlobalResourceObject("LocalizedText", "Wall_PendingRequest");
                LoadData();
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }

        protected void ShowComments_Click(object sender, EventArgs e)
        {
            try
            {
                LinkButton lkb = (sender as LinkButton);
                DataList dl = ControlFinder.FindControl<DataList>(lkb, "DataList2");
                if (dl.Visible == true)
                {
                    lkb.Text = (String)GetGlobalResourceObject("LocalizedText", "Common_ShowComments");
                    dl.Visible = false;
                }
                else
                {
                    lkb.Text = (String)GetGlobalResourceObject("LocalizedText", "Common_HideComments");
                    dl.Visible = true;
                }
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }

        protected List<Message> GetAllMessages(String userName)
        {
            try {
                List<Message> messages = WallBLL.GetAllPublicMessagesForUser(userName);
                foreach (Message m in messages)
                {
                    // Handle the publication date
                    if (int.Parse(m.PublicationAge) >= 60)
                    {
                        if (int.Parse(m.PublicationAge) >= 3600)
                        {
                            if (int.Parse(m.PublicationAge) >= 86400)
                            {
                                m.PublicationAge = Math.Floor(double.Parse(m.PublicationAge) / 86400.00).ToString() + " " + (String)GetGlobalResourceObject("LocalizedText", "Wall_PublicationAgeDaysAfter"); ;
                            }
                            else
                            {
                                m.PublicationAge = Math.Floor(double.Parse(m.PublicationAge) / 3600.00).ToString() + " " + (String)GetGlobalResourceObject("LocalizedText", "Wall_PublicationAgeHoursAfter");
                            }
                        }
                        else
                        {
                            m.PublicationAge = Math.Floor(double.Parse(m.PublicationAge) / 60.00).ToString() + " " + (String)GetGlobalResourceObject("LocalizedText", "Wall_PublicationAgeMinutesAfter");
                        }
                    }
                    else
                    {
                        m.PublicationAge += " " + (String)GetGlobalResourceObject("LocalizedText", "Wall_PublicationAgeSecondsAfter");
                    }
                    // Handle the friendship request
                    if (m.MessageContent.Trim().Equals(FriendshipBLL.FriendshipRequest))
                    {
                        m.MessageContent = m.SenderName + " " + (String)GetGlobalResourceObject("LocalizedText", "Wall_WouldYouBeMyFriend");
                    }
                    if (m.MessageContent.Trim().Equals(FriendshipBLL.FriendshipRequestAccepted))
                    {
                        m.MessageContent = m.SenderName + " " + (String)GetGlobalResourceObject("LocalizedText", "Wall_NewFriend");
                    }
                }
                return messages;
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }

        protected List<Comment> GetAllCommentsForMessage(String messageId)
        {
            try
            {
                List<Comment> comments = MessageBLL.GetAllCommentsForMessage(messageId);
                foreach (Comment c in comments)
                {
                    // Handle the publication date
                    if (int.Parse(c.PublicationAge) >= 60)
                    {
                        if (int.Parse(c.PublicationAge) >= 3600)
                        {
                            if (int.Parse(c.PublicationAge) >= 86400)
                            {
                                c.PublicationAge = Math.Floor(double.Parse(c.PublicationAge) / 86400.00).ToString() + " " + (String)GetGlobalResourceObject("LocalizedText", "Wall_PublicationAgeDaysAfter"); ;
                            }
                            else
                            {
                                c.PublicationAge = Math.Floor(double.Parse(c.PublicationAge) / 3600.00).ToString() + " " + (String)GetGlobalResourceObject("LocalizedText", "Wall_PublicationAgeHoursAfter");
                            }
                        }
                        else
                        {
                            c.PublicationAge = Math.Floor(double.Parse(c.PublicationAge) / 60.00).ToString() + " " + (String)GetGlobalResourceObject("LocalizedText", "Wall_PublicationAgeMinutesAfter");
                        }
                    }
                    else
                    {
                        c.PublicationAge += " " + (String)GetGlobalResourceObject("LocalizedText", "Wall_PublicationAgeSecondsAfter");
                    }
                }
                return comments;
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }

        [System.Web.Services.WebMethod]
        [System.Web.Script.Services.ScriptMethod]
        public static string[] GetUserNameList(string prefixText, int count, string contextKey)
        {
            try
            {
                String[] listUserNames = UserBLL.GetAllUserNames();
                return (from l in listUserNames where l.Contains(prefixText) select l).Take(count).ToArray();
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }
	}
}